<?php

namespace App\Models;

use function foo\func;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
use Laravel\Passport\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use App\Notifications\ResetPasswordNotification;
use App\Common\ConstCode;
class Role extends Authenticatable
{

    use HasApiTokens,Notifiable;


    protected $table = 'role_image';
    protected $fillable = ['type','category','cover_uri','tag','title','created_at','id','uid'];

    public    $timestamps = false;
    protected $primaryKey = 'id';

    /**
     * 所有素材列表
     * @param $data
     * @param $uid
     * @return array
     */
    public function lists($data,$uid){
        $category=$data['category'];
        $title=$data['title'];
        $where=[
            'type'=>ConstCode::YES,
            'status'=>ConstCode::YES,
            'is_shelf'=>ConstCode::YES,
        ];
        //我的包含私有
        $myCount=$this->count(['uid'=>$uid]);

        if($category) $where['category']=$category;
        if($title) $where[]=['title', 'LIKE', "%{$title}%"];
        $tag=$data['tag'];
        $result=DB::table('role_image')->where($where)
            ->when($tag,function($query,$tag){
                 if($tag){
                     $tag=explode(',',$tag);
                     foreach ($tag as $val){
                         $query->whereRaw('FIND_IN_SET(?,tag)',[$val]);
                     }
                 }
            })
            ->select($this->fillable)
            ->forPage($data['page'], $data['pageSize'])
            ->orderBy(ConstCode::COLUMN, ConstCode::DIRECTION)
            ->get()
            ->toArray();

        if($result){
            foreach ($result as &$val){
                if($uid==$val->uid){
                    $val->is_my=1;
                }else{
                    $val->is_my=0;
                }
                $val->cover_uri=uri_fill($val->cover_uri);
                $val->classify=config('cartoontag.ALBUM_TYPE.角色库');
            }
        }
        $curCount = $this->count($where,$tag);
        $data = [
            'list'   =>  $result,
            'myCount'  =>  $myCount,
            'curCount' =>  $curCount,
            'myCollect'=>  0
        ];
        return $data;
    }

    public function count($where,$tag=[]){
        $count=DB::table('role_image')->where($where)
            ->when($tag,function($query,$tag){
                if($tag){
                    $tag=explode(',',$tag);
                    foreach ($tag as $val){
                        $query->whereRaw('FIND_IN_SET(?,tag)',[$val]);
                    }
                }
            })
            ->count();
        return $count;
    }

    /**
     * 我的素材列表
     * @param $data
     * @param $uid
     * @return array
     */
    public function my_lists($data,$uid){
        $title=$data['title'];
        $where=['uid'=>$uid];

        if($title) $where[]=['title', 'LIKE', "%{$title}%"];
        $result=DB::table('role_image')->where($where)
            ->select('type','cover_uri','status','title','created_at','id')
            ->forPage($data['page'], $data['pageSize'])
            ->orderBy(ConstCode::COLUMN, ConstCode::DIRECTION)
            ->get()
            ->toArray();
        if($result){
            foreach ($result as &$val){
                $val->cover_uri=uri_fill($val->cover_uri);
            }
        }
        $curCount = $this->count($where);
        $data = [
            'list'   =>  $result,
            'total' =>  $curCount,
        ];
        return $data;
    }

    public function works_upload($data,$uid){
        $sources=$data['data'];
        $scene['uid']=$uid;
        $scene['type']=$data['is_open'];
        $scene['category']=$data['category'];
        $scene['title']=$data['title'];
        $scene['cover_uri']=$sources[0]['pic_uri'];
        $scene['category']=$data['category'];
        $scene['tag']=$data['tag'];
        DB::transaction(function () use($scene,$sources) {
            //添加主表
            $id=DB::table('role_image')->insertGetId($scene);
            foreach ($sources as $val){
                $picture['sid']=$id;
                $picture['pic_uri']=$val['pic_uri'];
                $picture['name']=$val['name'];
                $picture['type']=2;
                $picture['location']=$val['location'];
                DB::table('cartoon_picture')->insert($picture);
            }
        });

        return true;
    }

    /**
     * 待选择所有素材列表（包含我的私有）
     * @param $data
     * @return array
     */
    public function c_lists($data):array {
        $title=$data['title'];
        $where=[
            'status'=>ConstCode::YES,
            'is_shelf'=>ConstCode::YES,
            'category'=>$data['category']
        ];

        if($title) $where[]=['title', 'LIKE', "%{$title}%"];
        $tag=$data['tag'];

        $result=DB::table('role_image')->where($where)
            ->when($tag,function($query,$tag){
                if($tag){
                    $tag=explode(',',$tag);
                    foreach ($tag as $val){
                        $query->whereRaw('FIND_IN_SET(?,tag)',[$val]);
                    }
                }
            })
            ->where(function($query)use($data){
                $query->where('type',ConstCode::YES)
                    ->orwhere(function($query) use($data){
                        $query->where(['type'=>ConstCode::SECOND,'uid'=>$data['uid']]);
                    });
            })
            ->select($this->fillable)
            ->forPage($data['page'], $data['pageSize'])
            ->orderBy(ConstCode::COLUMN, ConstCode::DIRECTION)
            ->get()
            ->toArray();

        //获取预览图

        foreach ($result as $val){
            $hairs=DB::table('cartoon_picture')->where(['sid'=>$val->id,'type'=>config("cartoontag.ALBUM_TYPE.角色库"),'location'=>$data['location']])
                ->select(['front_hair','after_hair','sid','preview_uri','pic_uri'])->orderBy('id','asc')->first();
            $val->front_hair=$hairs->front_hair?$hairs->front_hair:'/cartoon/default.png';
            $val->after_hair=$hairs->after_hair?$hairs->after_hair:'/cartoon/default.png';
//            $val->preview_uri=$val->cover_uri;
            if($data['category']==4){
                //统一字段
                $val->preview_uri=$val->cover_uri;
            }else{
                $val->preview_uri=$val->cover_uri;
                $val->cover_uri=$hairs->pic_uri;
            }
        }
        $count=DB::table('role_image')->where($where)
            ->when($tag,function($query,$tag){
                if($tag){
                    $tag=explode(',',$tag);
                    foreach ($tag as $val){
                        $query->whereRaw('FIND_IN_SET(?,tag)',[$val]);
                    }
                }
            })
            ->where(function($query)use($data){
                $query->where('type',ConstCode::YES)
                    ->orwhere(function($query) use($data){
                        $query->where(['type'=>ConstCode::SECOND,'uid'=>$data['uid']]);
                    });
            })
            ->count();

        $data = [
            'list'   =>  $result,
            'total' =>  $count
        ];
        return $data;
    }
}
